import {Button, Input, message, Popconfirm, Space, Table, Tag} from "antd";
import {CreateRoleModel, UpdateRole} from "@/pages/authority/components";
import React, {useEffect, useState} from "react";
import {ColumnsType} from "antd/es/table";
import {deleteRole, pageRole} from "@/api/role";
import {DrawerRoleProp, RoleProp, RoleQueryProp} from "@/pages/authority/modules";

const AuthorityRolePage = () => {

    const columns: ColumnsType<RoleProp> = [
        {
            title: '序号',
            key: 'index',
            dataIndex: 'index',
            align: 'center',
            width: 50,
            render: (text, record, index) => <span>{index + 1}</span>,
        },
        {
            title: '角色名称',
            key: 'name',
            dataIndex: 'name',
            align: 'center',
        },
        {
            title: '角色编码',
            key: 'code',
            dataIndex: 'code',
            align: 'center',
            render: (text, record) => <Tag color="green">{record.code}</Tag>
        },
        {
            title: '描述',
            key: 'brief',
            dataIndex: 'brief',
            align: 'center',
        },
        {
            title: '创建时间',
            key: 'createTime',
            dataIndex: 'createTime',
            align: 'center',
        },
        {
            title: '操作',
            key: 'active',
            align: 'center',
            width: 150,
            render: (text, record, index) => (
                <Space size={'small'}>
                    <Button size="small" type="primary" onClick={() => openDrawer('edit', record)}>编辑</Button>
                    <Popconfirm
                        placement="left"
                        title="警告"
                        description="确认删除当前角色数据?"
                        onConfirm={() => deleteRoleHandler(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button size="small" type="primary" danger>删除</Button>
                    </Popconfirm>

                </Space>
            ),
        },
    ]

    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
    const [createVisible, setCreateVisible] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(false);
    const [datasource, setDatasource] = useState<RoleProp[]>([]);
    const [query, setQuery] = useState<RoleQueryProp>({page: 1, size: 10});
    const [total, setTotal] = useState<number>(0);
    const [drawerProp, setDrawerProp] = useState<DrawerRoleProp>({addVisible: false, editVisible: false});

    const loadData = async (data: RoleQueryProp) => {
        const {total, records} = await pageRole(data);
        setDatasource(records);
        setTotal(total);
    }

    const pageChange = (page: number, pageSize: number) => {

    }

    const openDrawer = (types: 'add' | 'edit', data: RoleProp) => {
        if (types === 'add') {
            setDrawerProp({data: data, editVisible: false, addVisible: true});
        }
        if (types ==='edit') {
            setDrawerProp({data: data, editVisible: true, addVisible: false});
        }
    }

    const closeDrawer = (types: 'add' | 'edit', isLoad: boolean, data?: RoleProp) => {
        setDrawerProp({data: undefined, editVisible: false, addVisible: false})
        if (isLoad) {
            loadData(query)
        }
    }

    const deleteRoleHandler = async (id?: number) => {
        await deleteRole(id? id.toString() : selectedRowKeys.toString());
        await loadData(query)
        message.success('删除成功')
    }

    useEffect(() => {
        loadData(query);
    }, [])


    return <>
        <Space>
            <Button type='primary' onClick={() => setCreateVisible(true)}>创建</Button>
            <Button type='primary' onClick={() => loadData(query)}>刷新</Button>
            <Button type='primary' danger onClick={() => deleteRoleHandler()} disabled={selectedRowKeys.length <= 0}>删除</Button>
            <Input placeholder="输入角色名称进行搜索" allowClear />
        </Space>
        <Table
            bordered
            size={'small'}
            loading={loading}
            columns={columns}
            dataSource={datasource}
            style={{ marginTop: 10 }}
            rowKey={(record) => record.id}
            pagination={{
                onShowSizeChange: (current, size) => loadData({...query, page: current, size: size}),
                onChange: (page, pageSize) => loadData({...query, page: page, size: pageSize}),
                showTotal: () => `共 ${total} 个`,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSize: query.size,
                current: query.page,
                size: 'default',
                total: total,
            }}
            rowSelection={{
                type: 'checkbox',
                selectedRowKeys: selectedRowKeys,
                onChange: (selectedRowKeys: React.Key[], selectedRows: RoleProp[]) => {
                    setSelectedRowKeys([...selectedRowKeys.map(item => item as number)])
                }
            }}
        />

        <CreateRoleModel
            visible={createVisible}
            onCancel={(isLoad) => setCreateVisible(false)}
        />
        <UpdateRole
            visible={drawerProp.editVisible}
            roleData={drawerProp.data}
            close={(isLoad, data) => closeDrawer('edit', isLoad, data)}
        />
    </>
}

export default AuthorityRolePage;